﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Dropthings.Test.Rules;

namespace Inventory.Test.Library.Rules
{
    [DisplayName("Extract Script Managers")]
    [Description("Extract any script manager found in the Http response")]
    public class ExtractScriptManagers : ExtractionRule
    {
        public const string SCRIPTMANAGER_PREFIX = "$SCRIPTMANAGER.";



        /// <summary>
        /// Extract ID of script manager from the provided string
        /// </summary>
        /// <param name="scriptManagerInitializationScript">For example:Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager1 </param>
        /// <returns></returns>
        static string GetEntityID(string scriptManagerInitializationScript)
        {
            if (string.IsNullOrEmpty(scriptManagerInitializationScript))
                throw new NullReferenceException("Cannont extract grid view id from empty string");

            int startIndex = scriptManagerInitializationScript.IndexOf('\'') + 1;

            string entityID = scriptManagerInitializationScript.Substring(startIndex);
            return entityID;

        }
        public static List<FormElement> Extract(string bodyString)
        {
            var formElements = new List<FormElement>();

            string pattern = "Sys.WebForms.PageRequestManager._initialize\\('(?<id>)([^']*)";

            Regex _FindAnchorTags = new Regex(
            pattern,
            RegexOptions.IgnoreCase
            | RegexOptions.Multiline
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );


            var extractMatches = _FindAnchorTags.Matches(bodyString);

            for (int i = 0; i < extractMatches.Count; i++)
            {
                Match extractMatch = extractMatches[i];

                string shortKey = SCRIPTMANAGER_PREFIX + i;
                string fullControlID = GetEntityID(extractMatch.Value);

                formElements.Add(new FormElement()
                {
                    ControlFullID = fullControlID,
                    ControlCategory = ControlCategory.SCRIPTMANAGER,
                    TempProperty = shortKey
                });
            }
            return formElements;
        }
        public override void Extract(object sender, ExtractionEventArgs e)
        {

            string body = e.Response.BodyString;
            var formElements = Extract(body);

            foreach (var element in formElements)
            {
                RuleHelper.PlaceIDSelector(e.WebTest.Context, element.ControlFullID);
                RuleHelper.PlaceIndexSelector(e.WebTest.Context, ControlCategory.SCRIPTMANAGER, element.TempProperty);
            }
            if (e.Success)
                e.Message = "Script Manager extracted.";
            else
                e.Message = "No script manager extracted.";
        }
    }
}
